//
//  LinePaymentVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2018/1/2.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "LinePaymentVC.h"

#import "AccountCouponVC.h"
#import "ContactService.h"
#import "IAPManager.h"
#import "WebViewVC.h"
#import "WXAlertVC.h"
#import "ADView.h"
#import "ChargeMoneyVC.h"
#import "PaySuccessAlert.h"

@interface LinePaymentVC ()
// 订单数据
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollTop;
@property (weak, nonatomic) IBOutlet UILabel *orderDescribeLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderNOLabel;
@property (weak, nonatomic) IBOutlet UIButton *funCopyBtn;

@property (weak, nonatomic) IBOutlet UIImageView *cityTourImageView;

@property (weak, nonatomic) IBOutlet UILabel *tourNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

// 优惠券数据
@property (weak, nonatomic) IBOutlet UIView *couponView;
@property (weak, nonatomic) IBOutlet UILabel *couponDesLabel;
@property (weak, nonatomic) IBOutlet UILabel *couponText;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *couponViewH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *couponViewTop;


//coinPriceLabel
// 支付方式
@property (weak, nonatomic) IBOutlet UILabel *coinDesLabel;
@property (weak, nonatomic) IBOutlet UIButton *coinBtn;
@property (weak, nonatomic) IBOutlet UILabel *coinPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *coinLeftLabel;

@property (weak, nonatomic) IBOutlet UILabel *iapDesLabel;
@property (weak, nonatomic) IBOutlet UIButton *chargeBtn;
@property (weak, nonatomic) IBOutlet UIButton *iapBtn;
@property (weak, nonatomic) IBOutlet UILabel *iapPriceLabel;
@property (weak, nonatomic) IBOutlet ADView *recommendView;

//支付帮助
@property (weak, nonatomic) IBOutlet UIView *helpView;
@property (weak, nonatomic) IBOutlet UILabel *payHelpTitle;
@property (weak, nonatomic) IBOutlet YYLabel *payHelpLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *payHelpLabelH;

//支付按钮
@property (weak, nonatomic) IBOutlet UIButton *confirmPaymentBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewH;

@property (nonatomic, strong) Coupon *coupon;
@property (nonatomic, strong) NSMutableArray *couponArray;

@property (nonatomic) PayType payType;

@property (nonatomic, strong) NSString *amount;// 线路的价格

@property (nonatomic) BOOL paying;


@end

@implementation LinePaymentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self setupData];
    self.isHiddenPlayStatusButton = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self reloadPriceView];
    
    [MobClick beginLogPageView:@"10"];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [MobClick endLogPageView:@"10"];
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

- (void)setupUI {
    
    
    self.coinDesLabel.text = MYLocalizedString(@"PAYORDER_TYPE_COIN", nil);
    self.iapDesLabel.text = MYLocalizedString(@"PAYORDER_TYPE_IAP", nil);
    self.recommendView.text = @"充值有礼";
    
    self.coinPriceLabel.textColor = kThemeColor;
    self.iapPriceLabel.textColor = kThemeColor;
    [self.chargeBtn setTitle:MYLocalizedString(@"COIN_TOPUP", nil) forState:UIControlStateNormal];
    
    self.scrollTop.constant = kNavigationBarHeight;
    [self closeAutomaticallyAdjustsScrollViewInsets:self.subScrollView];
    self.orderDescribeLabel.text = [NSString stringWithFormat:@"%@：",MYLocalizedString(@"MYORDER_ORDERNO", nil)];
    [self.funCopyBtn setTitle:MYLocalizedString(@"CONTACT_COPY", nil) forState:UIControlStateNormal];
    
    self.couponDesLabel.text = MYLocalizedString(@"PAYORDER_VOUCHER", nil);
    self.view.backgroundColor = kBGColor;
    self.confirmPaymentBtn.backgroundColor = kThemeColor;
    [self.confirmPaymentBtn setTitle:MYLocalizedString(@"PAYORDER_PAY", nil) forState:UIControlStateNormal];
    self.title = MYLocalizedString(@"PAYORDER_TITLE", nil);
    
    self.confirmPaymentBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.confirmPaymentBtn.titleLabel.numberOfLines = 0;
    
    self.payHelpLabel.numberOfLines = 0;
    self.payHelpLabel.attributedText = [self getYYLabelAttributedText];
    
    self.payHelpLabel.font = Font(14);
    CGFloat payHelpLabelH = [self.payHelpLabel sizeThatFits:CGSizeMake(kScreenWidth - 32, MAXFLOAT)].height;
    self.payHelpLabelH.constant = payHelpLabelH;
    
    self.scrollViewH.constant = 424.5 + 67 + payHelpLabelH + 16 + 8;
    self.isHiddenPlayStatusButton = NO;
//    [self rightBarButton:MYLocalizedString(@"PUBLIC_CANCEL", nil) color:[UIColor blackColor] selector:@selector(backAction)];
    [self barItemWithImageNameArray:@[@"back"] selArray:@[@"backAction"] isLeft:YES];
    
    if ([UserManager sharedManager].user.role != UserRolesTypeLow && [UserManager sharedManager].token) {
        
        self.couponView.hidden = NO;
        [self.couponView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseCouponAction)]];
    } else {
        
        self.couponView.hidden = YES;
        self.couponViewH.constant = 0;
        self.couponViewTop.constant = 0;
        
    }
    
    self.payType = PayTypeCoin;
    
    NSString *currencyCode = [AppManager sharedManager].currencyCode;
    
    if (![[currencyCode lowercaseStringWithLocale:[NSLocale currentLocale]] containsString:@"cn"]) {
        self.helpView.hidden = YES;
        return;
    }
    
    
}


- (void)setPayType:(PayType)payType {
    
    _payType = payType;
    
    if (payType == PayTypeCoin) {
        
        self.coinBtn.selected = YES;
        self.iapBtn.selected = NO;
    } else {
        
        self.coinBtn.selected = NO;
        self.iapBtn.selected = YES;
    }
    [self reloadPriceView];
}

/** 获取富文本 */
- (NSAttributedString *)getYYLabelAttributedText {
    
    NSString *textString = MYLocalizedString(@"PAYORDER_HELP_DES", nil);
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:textString];
    mutableAttributedString.font = Font(14);
    mutableAttributedString.color = kContentColor;
    mutableAttributedString.lineSpacing = 8;
    
    NSString *highlightString = MYLocalizedString(@"PAYORDER_HELP_DESHighlight", nil);
    
    NSRange range1 = [textString rangeOfString:highlightString];
    
    [mutableAttributedString setColor:kThemeColor range:range1];
    
    YYTextHighlight *stepHighlight = [YYTextHighlight highlightWithBackgroundColor:kBGColor];
    [mutableAttributedString setTextHighlight:stepHighlight range:range1];
    
    
    @weakify(self);
    stepHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        @strongify(self);
        WebViewVC *webVC = [WebViewVC new];
        webVC.url = @"https://mp.weixin.qq.com/s/y58rnOQSlMFHSNGuDdKdQQ";
        webVC.title = highlightString;
        [self.navigationController pushViewController:webVC animated:YES];
    };
    
    
    NSRange range2 = [textString rangeOfString:@"ImGuider"];
    [mutableAttributedString setColor:kThemeColor range:range2];
    
    YYTextHighlight *IGHighlight = [YYTextHighlight highlightWithBackgroundColor:kBGColor];
    [mutableAttributedString setTextHighlight:IGHighlight range:range2];
    
    IGHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        @strongify(self);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:@"ImGuider"];
        
        WXAlertVC *alertVC = [WXAlertVC new];
        
        [alertVC showWithVC:self];
    };
    
    return mutableAttributedString;
}


- (void)setupData {
    
    [self.cityTourImageView setImageURL:[NSURL URLWithString:self.lineModel.pictures] placeholderImage:[UIImage imageNamed:@"placeholder_squ"]];
    self.tourNameLabel.text = self.lineModel.linename;
    self.priceLabel.text = self.lineModel.price;
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    
    dispatch_group_t net_group = dispatch_group_create();
    dispatch_group_enter(net_group);
    
    @weakify(self);
    [NetAPIManager getMycouponsWithLineid:self.lineModel.lineid Block:^(NSArray<Coupon *> *couponArray, NSError *error) {
        @strongify(self);
        dispatch_group_leave(net_group);
        
        self.couponArray = [NSMutableArray arrayWithArray:couponArray];
    }];
    dispatch_group_enter(net_group);
    [NetAPIManager preorderOrderWithLineID:self.lineModel.lineid block:^(NSDictionary *result, NSError *error) {
        @strongify(self);
        dispatch_group_leave(net_group);
        if (result) {
            self.orderNOLabel.text = result[@"ordernumber"];
            [UserManager sharedManager].user.coin = [result[@"coin"] integerValue];
            self.amount = result[@"price"];
        }
    }];
    
    dispatch_group_notify(net_group, dispatch_get_main_queue(), ^{
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        [self reloadPriceView];
    });
}

- (void)backAction {
    
    if (self.paying) {
        return;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [MobClick event:@"10_1_2"];
}

- (IBAction)coinAction:(id)sender {
    
    self.payType = PayTypeCoin;
}
- (IBAction)iapAction:(id)sender {
    
    self.payType = PayTypeIAP;
}

- (IBAction)copyOrderNoAction:(id)sender {
    
    NSString *contact = self.orderNOLabel.text;
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = contact;
    
    [IGUtil showToast:MYLocalizedString(@"CONTACT_COPY_SUCCESS", nil)];
}

- (void)chooseCouponAction {
    
    AccountCouponVC *ticketVC = [IGUtil loadViewController:@"AccountCouponVC" storyboard:@"Account"];
    
    ticketVC.pageType = 1;
    ticketVC.dataSource = self.couponArray;
    ticketVC.delegate = self;
    
    [self.navigationController pushViewController:ticketVC animated:YES];
    
    [MobClick event:@"10_1_3"];
}

#pragma mark -AccountCouponVCDelegagte
- (void)selectCoupon:(Coupon *)coupon {
    
    self.coupon = coupon;
    [self reloadPriceView];
}

- (void)reloadPriceView {
    
    
    NSString *price = self.lineModel.price;
    NSString *coin = @(self.amount.floatValue / 100).stringValue;
    if (self.couponArray.count == 0) {
        
        self.couponText.text = MYLocalizedString(@"PAYORDER_NONE", nil);
        self.couponText.textColor = kContentColor;
    } else {
        self.couponText.textColor = kThemeColor;
    }
    
    if (self.coupon) {
        self.couponText.textColor = kThemeColor;
        self.couponText.text = [NSString stringWithFormat:@"%@%@",self.coupon.infos[@"big"],self.coupon.infos[@"middle"]];
        price = self.coupon.infos[@"feestring"];
        coin = @([self.coupon.infos[@"fee"] floatValue] / 100).stringValue;
    } else {
        self.couponText.text = [NSString localizedStringWithFormat:MYLocalizedString(@"PAYORDER_TOTAL", nil),@(self.couponArray.count)];
    }
    
    self.coinPriceLabel.text = [NSString stringWithFormat:@"%@%@",coin,MYLocalizedString(@"PUBLIC_COIN_NAME", nil)];
    self.iapPriceLabel.text = price;
    self.coinLeftLabel.text = [NSString stringWithFormat:@"%@:%@%@",MYLocalizedString(@"COIN_BALANCE", nil),@([UserManager sharedManager].user.coin).stringValue,MYLocalizedString(@"PUBLIC_COIN_NAME", nil)];
    
    if (self.lineModel.song.length > 0 && self.lineModel.song.integerValue > 0 && coin.integerValue > 0) {
        
        NSInteger song = ceil(coin.floatValue * self.lineModel.song.floatValue / 100);
        
        NSMutableAttributedString *text1 = [[NSMutableAttributedString alloc] initWithString:MYLocalizedString(@"PAYORDER_PAY", nil)];
        text1.alignment = NSTextAlignmentCenter;
        text1.font = Font(17);
        text1.lineSpacing = 5;
        
        NSMutableAttributedString *text2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\n（限时活动 支付成功即送%ldG币）",(long)song]];
        text2.font = Font(12);
        
        [text1 appendAttributedString:text2];
        
        
        [self.confirmPaymentBtn setAttributedTitle:text1 forState:UIControlStateNormal];
        
    } else {

        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:MYLocalizedString(@"PAYORDER_PAY", nil)];
        text.alignment = NSTextAlignmentCenter;
        
        text.font = Font(17);
        [self.confirmPaymentBtn setAttributedTitle:text forState:UIControlStateNormal];
    }
    
    if ([UserManager sharedManager].user.coin < coin.integerValue && self.payType == PayTypeCoin) {
        
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:MYLocalizedString(@"PAYORDER_COIN_NO_BALANCE", nil)];
        text.alignment = NSTextAlignmentCenter;
        
        text.font = Font(17);
        [self.confirmPaymentBtn setAttributedTitle:text forState:UIControlStateNormal];
    }
}

- (IBAction)coinBtnAcion:(id)sender {
    
    self.coinBtn.selected = YES;
    self.iapBtn.selected = NO;
}
//原来程序员这一行也像围城一样：外行人想进来，内行人想出去
- (IBAction)iapBtnAction:(id)sender {
    
    self.coinBtn.selected = NO;
    self.iapBtn.selected = YES;
}

- (IBAction)chargeMoneyAction:(id)sender {
    
    ChargeMoneyVC *moneyVC = [IGUtil loadViewController:@"ChargeMoneyVC" storyboard:@"Account"];
    
    [self.navigationController pushViewController:moneyVC animated:YES];
}


- (IBAction)confirmPaymentBtnClicked:(UIButton *)sender {
    
    [MobClick event:@"10_1_4"];
    
    NSInteger coin = self.amount.floatValue / 100;
    if (self.coupon) {
        coin = [self.coupon.infos[@"fee"] floatValue] / 100;
    }
    
    if ([UserManager sharedManager].user.coin < coin && self.payType == PayTypeCoin) {
        
        [self chargeMoneyAction:nil];
        return;
    }
    
    self.paying = YES;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    @weakify(self);
    
    
    [[IAPManager sharedManager] paymentID:self.lineModel.lineid couponid:self.coupon.couponid payType:self.payType ordernumber:self.orderNOLabel.text merchType:MerchTypeLine andBlock:^(id result, NSError *error) {
        
        @strongify(self);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.paying = NO;
        
        if (!error) {
            [IGUtil showToast:MYLocalizedString(@"PAYORDER_SUCCESS", nil)];
            
            if ([_delegate respondsToSelector:@selector(paySuccessCallback)]) {
                [_delegate paySuccessCallback];
            }
            //            虚拟币购买 或者 使用优惠券 需要刷新我的界面，更新虚拟币数量 和 优惠券数量
            if (self.payType == PayTypeCoin || self.coupon.couponid.length > 0 || self.lineModel.song) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kReloadUserDataNotif object:nil];
            }
            
            if (self.lineModel.song.length > 0 && self.lineModel.song.integerValue > 0) {
                
                if (![result isKindOfClass:[NSDictionary class]]) {
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    [self dismissViewControllerAnimated:YES completion:nil];
                    return ;
                }
                
                NSInteger song = [result[@"song"] integerValue];
                
                if (song <= 0) {
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    [self dismissViewControllerAnimated:YES completion:nil];
                    return;
                }
   
                PaySuccessAlert *alertVC = [PaySuccessAlert new];
                alertVC.dict = result;
                @weakify(self);
                [alertVC showWithVC:self block:^{
                    @strongify(self);
                    [self.navigationController popViewControllerAnimated:YES];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                
                return;
            }
            
            [self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
            
            return;
        }
        
        if (error.code == PAY_FILEDCOED_SERVERERROR) {
            
            [IGAlertView alertWithTitle:MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil) message:MYLocalizedString(@"PAYORDER_FAILED_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYORDER_CONTACTSTAFF", nil) commit:^{
                UIViewController *contactService = [IGUtil loadViewController:@"ContactService" storyboard:@"Account"];
                [self.navigationController pushViewController:contactService animated:YES];
            } cancel:nil];
            
        } else {
            
            [IGUtil showToast:[IGUtil tipFromError:error]];
        }
        return;
        
    }];
}
@end


